import com.alibaba.fastjson.JSONObject;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author : lzp
 * @version 1.0
 * @date : 2021/11/24 16:38
 * @apiNote : 不完整的身份证校验正则(最后一位是校验码,需要前15位各自加权相乘再取余结果后得出)
 */
public class RegIdCard {
    public static final Pattern ID = Pattern.compile("^\\d{6}(?<year>[1-2]\\d{3})(?<month>(0[1-9]|11|12))(?<day>(0[1-9]|[1-2][0-9]|30|31))\\d{2}(?<sex>\\d)[\\dXx]$");
    public static void main(String[] args) {
        String id="450323199712162713";
        Matcher matcher = ID.matcher(id);
        if (matcher.find()){
            //出生日期
            String sb = matcher.group("year") + '-' + matcher.group("month") + '-' + matcher.group("day");
            LocalDateTime localDateTime = LocalDateTime.parse(sb + " 00:00:00",DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            System.out.println(localDateTime.toString());
            //性别编码
            String sex = matcher.group("sex");
            System.out.println(Integer.parseInt(sex) % 2 == 0 ? "女" : "男");
            //年龄
            Calendar nowCal = Calendar.getInstance();
            Calendar birCal = Calendar.getInstance();
            ZoneId zoneId = ZoneId.systemDefault();
            ZonedDateTime zonedDateTime = localDateTime.atZone(zoneId);
            birCal.setTime(Date.from(zonedDateTime.toInstant()));

            int nowYear = nowCal.get(Calendar.YEAR);
            int nowMonth = nowCal.get(Calendar.MONTH);
            int nowDay = nowCal.get(Calendar.DAY_OF_MONTH);

            int birYear = birCal.get(Calendar.YEAR);
            int birMonth = birCal.get(Calendar.MONTH);
            int birDay = birCal.get(Calendar.DAY_OF_MONTH);
            /*大概年龄是当前年减去出生年*/
            int age = nowYear - birYear;
            /*如果出当前月小与出生月，或者当前月等于出生月但是当前日小于出生日，那么年龄age就减一岁*/
            if (nowMonth < birMonth || (nowMonth == birMonth && nowDay < birDay)) {
                age--;
            }
            System.out.println("age:"+age);
        }
    }
}
